home *** CD-ROM | disk | FTP | other *** search
/ Aminet 32 / Aminet 32 (1999)(Schatztruhe)[!][Aug 1999].iso / Aminet / dev / lang / Python152_Src.lha / Python152_Source / Modules / socketmodule.c < prev    next >
C/C++ Source or Header  |  1999-04-27  |  60KB  |  2,318 lines

  1. /***********************************************************
  2. Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam,
  3. The Netherlands.
  4.  
  5.                         All Rights Reserved
  6.  
  7. Permission to use, copy, modify, and distribute this software and its
  8. documentation for any purpose and without fee is hereby granted,
  9. provided that the above copyright notice appear in all copies and that
  10. both that copyright notice and this permission notice appear in
  11. supporting documentation, and that the names of Stichting Mathematisch
  12. Centrum or CWI or Corporation for National Research Initiatives or
  13. CNRI not be used in advertising or publicity pertaining to
  14. distribution of the software without specific, written prior
  15. permission.
  16.  
  17. While CWI is the initial source for this software, a modified version
  18. is made available by the Corporation for National Research Initiatives
  19. (CNRI) at the Internet address ftp://ftp.python.org.
  20.  
  21. STICHTING MATHEMATISCH CENTRUM AND CNRI DISCLAIM ALL WARRANTIES WITH
  22. REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF
  23. MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH
  24. CENTRUM OR CNRI BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
  25. DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
  26. PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  27. TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  28. PERFORMANCE OF THIS SOFTWARE.
  29.  
  30. ******************************************************************/
  31.  
  32. /* Socket module */
  33.  
  34. /*
  35. This module provides an interface to Berkeley socket IPC.
  36.  
  37. Limitations:
  38.  
  39. - only AF_INET and AF_UNIX address families are supported
  40. - no read/write operations (use send/recv or makefile instead)
  41. - additional restrictions apply on Windows
  42.  
  43. Module interface:
  44.  
  45. - socket.error: exception raised for socket specific errors
  46. - socket.gethostbyname(hostname) --> host IP address (string: 'dd.dd.dd.dd')
  47. - socket.gethostbyaddr(IP address) --> (hostname, [alias, ...], [IP addr, ...])
  48. - socket.gethostname() --> host name (string: 'spam' or 'spam.domain.com')
  49. - socket.getprotobyname(protocolname) --> protocol number
  50. - socket.getservbyname(servicename, protocolname) --> port number
  51. - socket.socket(family, type [, proto]) --> new socket object
  52. - socket.ntohs(16 bit value) --> new int object
  53. - socket.ntohl(32 bit value) --> new int object
  54. - socket.htons(16 bit value) --> new int object
  55. - socket.htonl(32 bit value) --> new int object
  56. - socket.AF_INET, socket.SOCK_STREAM, etc.: constants from <socket.h>
  57. - an Internet socket address is a pair (hostname, port)
  58.   where hostname can be anything recognized by gethostbyname()
  59.   (including the dd.dd.dd.dd notation) and port is in host byte order
  60. - where a hostname is returned, the dd.dd.dd.dd notation is used
  61. - a UNIX domain socket address is a string specifying the pathname
  62.  
  63. Socket methods:
  64.  
  65. - s.accept() --> new socket object, sockaddr
  66. - s.bind(sockaddr) --> None
  67. - s.close() --> None
  68. - s.connect(sockaddr) --> None
  69. - s.connect_ex(sockaddr) --> 0 or errno (handy for e.g. async connect)
  70. - s.fileno() --> file descriptor
  71. - s.dup() --> same as socket.fromfd(os.dup(s.fileno(), ...)
  72. - s.getpeername() --> sockaddr
  73. - s.getsockname() --> sockaddr
  74. - s.getsockopt(level, optname[, buflen]) --> int or string
  75. - s.listen(backlog) --> None
  76. - s.makefile([mode[, bufsize]]) --> file object
  77. - s.recv(buflen [,flags]) --> string
  78. - s.recvfrom(buflen [,flags]) --> string, sockaddr
  79. - s.send(string [,flags]) --> nbytes
  80. - s.sendto(string, [flags,] sockaddr) --> nbytes
  81. - s.setblocking(0 | 1) --> None
  82. - s.setsockopt(level, optname, value) --> None
  83. - s.shutdown(how) --> None
  84. - repr(s) --> "<socket object, fd=%d, family=%d, type=%d, protocol=%d>"
  85.  
  86. */
  87.  
  88. #include "Python.h"
  89.  
  90. #undef HAVE_GETHOSTBYNAME_R_3_ARG
  91. #undef HAVE_GETHOSTBYNAME_R_5_ARG
  92. #undef HAVE_GETHOSTBYNAME_R_6_ARG
  93.  
  94. #ifndef WITH_THREAD
  95. #undef HAVE_GETHOSTBYNAME_R
  96. #endif
  97.  
  98. #ifdef HAVE_GETHOSTBYNAME_R
  99. #if defined(_AIX) || defined(__osf__)
  100. #define HAVE_GETHOSTBYNAME_R_3_ARG
  101. #elif defined(__sun__) || defined(__sgi)
  102. #define HAVE_GETHOSTBYNAME_R_5_ARG
  103. #elif defined(linux)
  104. #define HAVE_GETHOSTBYNAME_R_6_ARG
  105. #else
  106. #undef HAVE_GETHOSTBYNAME_R
  107. #endif
  108. #endif
  109.  
  110. #if !defined(HAVE_GETHOSTBYNAME_R) && defined(WITH_THREAD) && !defined(MS_WINDOWS)
  111. #define USE_GETHOSTBYNAME_LOCK
  112. #endif
  113.  
  114. #ifdef USE_GETHOSTBYNAME_LOCK
  115. #include "pythread.h"
  116. #endif
  117.  
  118. #ifdef HAVE_UNISTD_H
  119. #include <unistd.h>
  120. #endif
  121.  
  122. #if !defined(MS_WINDOWS) && !defined(PYOS_OS2) && !defined(__BEOS__) && !defined(_AMIGA)
  123. extern int gethostname(); /* For Solaris, at least */
  124. #endif
  125.  
  126. #if defined(PYCC_VACPP)
  127. #include <types.h>
  128. #include <io.h>
  129. #include <sys/ioctl.h>
  130. #include <utils.h>
  131. #include <ctype.h>
  132. #endif
  133.  
  134. #if defined(PYOS_OS2)
  135. #define  INCL_DOS
  136. #define  INCL_DOSERRORS
  137. #define  INCL_NOPMAPI
  138. #include <os2.h>
  139. #endif
  140.  
  141. #if defined(__BEOS__)
  142. /* It's in the libs, but not the headers... - [cjh] */
  143. int shutdown( int, int );
  144. #endif
  145.  
  146. #include <sys/types.h>
  147. #include "mytime.h"
  148.  
  149. #include <signal.h>
  150. #ifndef MS_WINDOWS
  151. #include <netdb.h>
  152. #include <sys/socket.h>
  153. #include <netinet/in.h>
  154. #include <fcntl.h>
  155. #else
  156. #include <winsock.h>
  157. #include <fcntl.h>
  158. #endif
  159. #if defined(AMITCP) || defined(INET225)
  160. #define SYS_TTYCHARS_H
  161. #include <sys/ioctl.h>
  162. #include <proto/socket.h>
  163. #endif
  164. #ifdef HAVE_SYS_UN_H
  165. #include <sys/un.h>
  166. #else
  167. #undef AF_UNIX
  168. #endif
  169.  
  170. #ifndef O_NDELAY
  171. #define O_NDELAY O_NONBLOCK    /* For QNX only? */
  172. #endif
  173.  
  174. #ifdef USE_GUSI
  175. /* fdopen() isn't declared in stdio.h (sigh) */
  176. #include <GUSI.h>
  177. #endif
  178.  
  179. #include "protos/socketmodule.h"
  180.  
  181. /* Here we have some hacks to choose between K&R or ANSI style function
  182.    definitions.  For NT to build this as an extension module (ie, DLL)
  183.    it must be compiled by the C++ compiler, as it takes the address of
  184.    a static data item exported from the main Python DLL.
  185. */
  186. #if defined(MS_WINDOWS) || defined(__BEOS__)
  187. /* BeOS suffers from the same socket dichotomy as Win32... - [cjh] */
  188. /* seem to be a few differences in the API */
  189. #define close closesocket
  190. #define NO_DUP /* Actually it exists on NT 3.5, but what the heck... */
  191. #define FORCE_ANSI_FUNC_DEFS
  192. #endif
  193.  
  194. #if defined(PYOS_OS2)
  195. #define close soclose
  196. #define NO_DUP /* Sockets are Not Actual File Handles under OS/2 */
  197. #define FORCE_ANSI_FUNC_DEFS
  198. #endif
  199.  
  200. #ifdef AMITCP
  201. /* seem to be a few differences in the API */
  202. //#define close CloseSocket
  203. #define ioctlsocket IoctlSocket
  204. #undef NO_DUP
  205. #undef AF_UNIX
  206. #define FORCE_ANSI_FUNC_DEFS
  207. #endif
  208.  
  209. #ifdef INET225
  210. /* seem to be a few differences in the API */
  211. #define close s_close
  212. #define ioctlsocket s_ioctl
  213. #undef NO_DUP
  214. static __inline int dup(int oldsd) { return s_dup(oldsd); }
  215. #undef AF_UNIX
  216. #define FORCE_ANSI_FUNC_DEFS
  217. #endif
  218.  
  219. #ifdef FORCE_ANSI_FUNC_DEFS
  220. #define BUILD_FUNC_DEF_1( fnname, arg1type, arg1name )    \
  221. fnname( arg1type arg1name )
  222.  
  223. #define BUILD_FUNC_DEF_2( fnname, arg1type, arg1name, arg2type, arg2name ) \
  224. fnname( arg1type arg1name, arg2type arg2name )
  225.  
  226. #define BUILD_FUNC_DEF_3( fnname, arg1type, arg1name, arg2type, arg2name , arg3type, arg3name )    \
  227. fnname( arg1type arg1name, arg2type arg2name, arg3type arg3name )
  228.  
  229. #define BUILD_FUNC_DEF_4( fnname, arg1type, arg1name, arg2type, arg2name , arg3type, arg3name, arg4type, arg4name )    \
  230. fnname( arg1type arg1name, arg2type arg2name, arg3type arg3name, arg4type arg4name )
  231.  
  232. #else /* !FORCE_ANSI_FN_DEFS */
  233. #define BUILD_FUNC_DEF_1( fnname, arg1type, arg1name )    \
  234. fnname( arg1name )    \
  235.     arg1type arg1name;
  236.  
  237. #define BUILD_FUNC_DEF_2( fnname, arg1type, arg1name, arg2type, arg2name ) \
  238. fnname( arg1name, arg2name )    \
  239.     arg1type arg1name;    \
  240.     arg2type arg2name;
  241.  
  242. #define BUILD_FUNC_DEF_3( fnname, arg1type, arg1name, arg2type, arg2name, arg3type, arg3name ) \
  243. fnname( arg1name, arg2name, arg3name )    \
  244.     arg1type arg1name;    \
  245.     arg2type arg2name;    \
  246.     arg3type arg3name;
  247.  
  248. #define BUILD_FUNC_DEF_4( fnname, arg1type, arg1name, arg2type, arg2name, arg3type, arg3name, arg4type, arg4name ) \
  249. fnname( arg1name, arg2name, arg3name, arg4name )    \
  250.     arg1type arg1name;    \
  251.     arg2type arg2name;    \
  252.     arg3type arg3name;    \
  253.     arg4type arg4name;
  254.  
  255. #endif /* !FORCE_ANSI_FN_DEFS */
  256.  
  257. /* Global variable holding the exception type for errors detected
  258.    by this module (but not argument type or memory errors, etc.). */
  259.  
  260. static PyObject *PySocket_Error;
  261.  
  262.  
  263. /* Convenience function to raise an error according to errno
  264.    and return a NULL pointer from a function. */
  265.  
  266. static PyObject *
  267. PySocket_Err()
  268. {
  269. #ifdef MS_WINDOWS
  270.     if (WSAGetLastError()) {
  271.         PyObject *v;
  272.         v = Py_BuildValue("(is)", WSAGetLastError(), "winsock error");
  273.         if (v != NULL) {
  274.             PyErr_SetObject(PySocket_Error, v);
  275.             Py_DECREF(v);
  276.         }
  277.         return NULL;
  278.     }
  279.     else
  280. #endif
  281.  
  282. #if defined(PYOS_OS2)
  283.     if (sock_errno() != NO_ERROR) {
  284.         APIRET rc;
  285.         ULONG  msglen;
  286.         char   outbuf[100];
  287.         int    myerrorcode = sock_errno();
  288.  
  289.         /* Retrieve Socket-Related Error Message from MPTN.MSG File */
  290.         rc = DosGetMessage(NULL, 0, outbuf, sizeof(outbuf),
  291.                            myerrorcode - SOCBASEERR + 26, "mptn.msg", &msglen);
  292.         if (rc == NO_ERROR) {
  293.             PyObject *v;
  294.  
  295.             outbuf[msglen] = '\0'; /* OS/2 Doesn't Guarantee a Terminator */
  296.             if (strlen(outbuf) > 0) { /* If Non-Empty Msg, Trim CRLF */
  297.                 char *lastc = &outbuf[ strlen(outbuf)-1 ];
  298.                 while (lastc > outbuf && isspace(*lastc))
  299.                     *lastc-- = '\0'; /* Trim Trailing Whitespace (CRLF) */
  300.             }
  301.             v = Py_BuildValue("(is)", myerrorcode, outbuf);
  302.             if (v != NULL) {
  303.                 PyErr_SetObject(PySocket_Error, v);
  304.                 Py_DECREF(v);
  305.             }
  306.             return NULL;
  307.         }
  308.     }
  309. #endif
  310.  
  311.     return PyErr_SetFromErrno(PySocket_Error);
  312. }
  313.  
  314.  
  315. /* The object holding a socket.  It holds some extra information,
  316.    like the address family, which is used to decode socket address
  317.    arguments properly. */
  318.  
  319. typedef struct {
  320.     PyObject_HEAD
  321.     int sock_fd;        /* Socket file descriptor */
  322.     int sock_family;    /* Address family, e.g., AF_INET */
  323.     int sock_type;        /* Socket type, e.g., SOCK_STREAM */
  324.     int sock_proto;        /* Protocol type, usually 0 */
  325.     union sock_addr {
  326.         struct sockaddr_in in;
  327. #ifdef AF_UNIX
  328.         struct sockaddr_un un;
  329. #endif
  330.     } sock_addr;
  331. } PySocketSockObject;
  332.  
  333.  
  334. /* A forward reference to the Socktype type object.
  335.    The Socktype variable contains pointers to various functions,
  336.    some of which call newsockobject(), which uses Socktype, so
  337.    there has to be a circular reference. */
  338.  
  339. staticforward PyTypeObject PySocketSock_Type;
  340.  
  341.  
  342. /* Create a new socket object.
  343.    This just creates the object and initializes it.
  344.    If the creation fails, return NULL and set an exception (implicit
  345.    in NEWOBJ()). */
  346.  
  347. static PySocketSockObject *
  348. BUILD_FUNC_DEF_4(PySocketSock_New,int,fd, int,family, int,type, int,proto)
  349. {
  350.     PySocketSockObject *s;
  351.     PySocketSock_Type.ob_type = &PyType_Type;
  352.     s = PyObject_NEW(PySocketSockObject, &PySocketSock_Type);
  353.     if (s != NULL) {
  354.         s->sock_fd = fd;
  355.         s->sock_family = family;
  356.         s->sock_type = type;
  357.         s->sock_proto = proto;
  358. #if defined(AMITCP) || defined (INET225)
  359.         /* Amiga's TCP stacks want a zeroed out sock_addr structure */
  360.         memset(&s->sock_addr, 0, sizeof(s->sock_addr));
  361. #ifdef AMITCP
  362.         if(family==AF_INET) s->sock_addr.in.sin_len=sizeof(struct sockaddr_in);
  363. #ifdef AF_UNIX
  364.         if(family==AF_UNIX) s->sock_addr.un.sun_len=sizeof(struct sockaddr_un);
  365. #endif /* AF_UNIX */
  366. #endif /* AMITCP */
  367. #endif /* AMITCP || INET225 */
  368.     }
  369.     return s;
  370. }
  371.  
  372.  
  373. /* Lock to allow python interpreter to continue, but only allow one 
  374.    thread to be in gethostbyname */
  375. #ifdef USE_GETHOSTBYNAME_LOCK
  376. PyThread_type_lock gethostbyname_lock;
  377. #endif
  378.  
  379.  
  380. /* Convert a string specifying a host name or one of a few symbolic
  381.    names to a numeric IP address.  This usually calls gethostbyname()
  382.    to do the work; the names "" and "<broadcast>" are special.
  383.    Return the length (should always be 4 bytes), or negative if
  384.    an error occurred; then an exception is raised. */
  385.  
  386. static int
  387. BUILD_FUNC_DEF_2(setipaddr, char*,name, struct sockaddr_in *,addr_ret)
  388. {
  389.     struct hostent *hp;
  390.     int d1, d2, d3, d4;
  391.     int h_length;
  392.     char ch;
  393. #ifdef HAVE_GETHOSTBYNAME_R
  394.     struct hostent hp_allocated;
  395. #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
  396.     struct hostent_data data;
  397. #else
  398.     char buf[1001];
  399.     int buf_len = (sizeof buf) - 1;
  400.     int errnop;
  401. #endif
  402. #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
  403.     int result;
  404. #endif
  405. #endif /* HAVE_GETHOSTBYNAME_R */
  406.  
  407.     memset((void *) addr_ret, '\0', sizeof(*addr_ret));
  408.     if (name[0] == '\0') {
  409.         addr_ret->sin_addr.s_addr = INADDR_ANY;
  410.         return 4;
  411.     }
  412.     if (name[0] == '<' && strcmp(name, "<broadcast>") == 0) {
  413.         addr_ret->sin_addr.s_addr = INADDR_BROADCAST;
  414.         return 4;
  415.     }
  416.     if (sscanf(name, "%d.%d.%d.%d%c", &d1, &d2, &d3, &d4, &ch) == 4 &&
  417.         0 <= d1 && d1 <= 255 && 0 <= d2 && d2 <= 255 &&
  418.         0 <= d3 && d3 <= 255 && 0 <= d4 && d4 <= 255) {
  419.         addr_ret->sin_addr.s_addr = htonl(
  420.             ((long) d1 << 24) | ((long) d2 << 16) |
  421.             ((long) d3 << 8) | ((long) d4 << 0));
  422.         return 4;
  423.     }
  424.     Py_BEGIN_ALLOW_THREADS
  425. #ifdef HAVE_GETHOSTBYNAME_R
  426. #if    defined(HAVE_GETHOSTBYNAME_R_6_ARG)
  427.     result = gethostbyname_r(name, &hp_allocated, buf, buf_len, &hp, &errnop);
  428. #elif  defined(HAVE_GETHOSTBYNAME_R_5_ARG)
  429.     hp = gethostbyname_r(name, &hp_allocated, buf, buf_len, &errnop);
  430. #else  /* HAVE_GETHOSTBYNAME_R_3_ARG */
  431.     memset((void *) &data, '\0', sizeof(data));
  432.     result = gethostbyname_r(name, &hp_allocated, &data);
  433.     hp = (result != 0) ? NULL : &hp_allocated;
  434. #endif
  435. #else /* not HAVE_GETHOSTBYNAME_R */
  436. #ifdef USE_GETHOSTBYNAME_LOCK
  437.     PyThread_acquire_lock(gethostbyname_lock, 1);
  438. #endif
  439.     hp = gethostbyname(name);
  440. #endif /* HAVE_GETHOSTBYNAME_R */
  441.     Py_END_ALLOW_THREADS
  442.  
  443.     if (hp == NULL) {
  444. #ifdef HAVE_HSTRERROR
  445.             /* Let's get real error message to return */
  446.             extern int h_errno;
  447.         PyErr_SetString(PySocket_Error, (char *)hstrerror(h_errno));
  448. #else
  449.         PyErr_SetString(PySocket_Error, "host not found");
  450. #endif
  451. #ifdef USE_GETHOSTBYNAME_LOCK
  452.         PyThread_release_lock(gethostbyname_lock);
  453. #endif
  454.         return -1;
  455.     }
  456.     memcpy((char *) &addr_ret->sin_addr, hp->h_addr, hp->h_length);
  457.     h_length = hp->h_length;
  458. #ifdef USE_GETHOSTBYNAME_LOCK
  459.     PyThread_release_lock(gethostbyname_lock);
  460. #endif
  461.     return h_length;
  462. }
  463.  
  464.  
  465. /* Create a string object representing an IP address.
  466.    This is always a string of the form 'dd.dd.dd.dd' (with variable
  467.    size numbers). */
  468.  
  469. static PyObject *
  470. BUILD_FUNC_DEF_1(makeipaddr, struct sockaddr_in *,addr)
  471. {
  472.     long x = ntohl(addr->sin_addr.s_addr);
  473.     char buf[100];
  474.     sprintf(buf, "%d.%d.%d.%d",
  475.         (int) (x>>24) & 0xff, (int) (x>>16) & 0xff,
  476.         (int) (x>> 8) & 0xff, (int) (x>> 0) & 0xff);
  477.     return PyString_FromString(buf);
  478. }
  479.  
  480.  
  481. /* Create an object representing the given socket address,
  482.    suitable for passing it back to bind(), connect() etc.
  483.    The family field of the sockaddr structure is inspected
  484.    to determine what kind of address it really is. */
  485.  
  486. /*ARGSUSED*/
  487. static PyObject *
  488. BUILD_FUNC_DEF_2(makesockaddr,struct sockaddr *,addr, int,addrlen)
  489. {
  490.     if (addrlen == 0) {
  491.         /* No address -- may be recvfrom() from known socket */
  492.         Py_INCREF(Py_None);
  493.         return Py_None;
  494.     }
  495.  
  496. #ifdef __BEOS__
  497.     /* XXX: BeOS version of accept() doesn't set family coreectly */
  498.     addr->sa_family = AF_INET;
  499. #endif
  500.  
  501.     switch (addr->sa_family) {
  502.  
  503.     case AF_INET:
  504.     {
  505.         struct sockaddr_in *a = (struct sockaddr_in *) addr;
  506.         PyObject *addrobj = makeipaddr(a);
  507.         PyObject *ret = NULL;
  508.         if (addrobj) {
  509.             ret = Py_BuildValue("Oi", addrobj, ntohs(a->sin_port));
  510.             Py_DECREF(addrobj);
  511.         }
  512.         return ret;
  513.     }
  514.  
  515. #ifdef AF_UNIX
  516.     case AF_UNIX:
  517.     {
  518.         struct sockaddr_un *a = (struct sockaddr_un *) addr;
  519.         return PyString_FromString(a->sun_path);
  520.     }
  521. #endif /* AF_UNIX */
  522.  
  523.     /* More cases here... */
  524.  
  525.     default:
  526.         /* If we don't know the address family, don't raise an
  527.            exception -- return it as a tuple. */
  528.         return Py_BuildValue("is#",
  529.                      addr->sa_family,
  530.                      addr->sa_data,
  531.                      sizeof(addr->sa_data));
  532.  
  533.     }
  534. }
  535.  
  536.  
  537. /* Parse a socket address argument according to the socket object's
  538.    address family.  Return 1 if the address was in the proper format,
  539.    0 of not.  The address is returned through addr_ret, its length
  540.    through len_ret. */
  541.  
  542. static int
  543. BUILD_FUNC_DEF_4(
  544. getsockaddrarg,PySocketSockObject *,s, PyObject *,args, struct sockaddr **,addr_ret, int *,len_ret)
  545. {
  546.     switch (s->sock_family) {
  547.  
  548. #ifdef AF_UNIX
  549.     case AF_UNIX:
  550.     {
  551.         struct sockaddr_un* addr;
  552.         char *path;
  553.         int len;
  554.         addr = (struct sockaddr_un* )&(s->sock_addr).un;
  555.         if (!PyArg_Parse(args, "t#", &path, &len))
  556.             return 0;
  557.         if (len > sizeof addr->sun_path) {
  558.             PyErr_SetString(PySocket_Error,
  559.                     "AF_UNIX path too long");
  560.             return 0;
  561.         }
  562.         addr->sun_family = AF_UNIX;
  563.         memcpy(addr->sun_path, path, len);
  564.         addr->sun_path[len] = 0;
  565.         *addr_ret = (struct sockaddr *) addr;
  566.         *len_ret = len + sizeof(*addr) - sizeof(addr->sun_path);
  567.         return 1;
  568.     }
  569. #endif /* AF_UNIX */
  570.  
  571.     case AF_INET:
  572.     {
  573.         struct sockaddr_in* addr;
  574.         char *host;
  575.         int port;
  576.          addr=(struct sockaddr_in*)&(s->sock_addr).in;
  577.         if (!PyArg_Parse(args, "(si)", &host, &port))
  578.             return 0;
  579.         if (setipaddr(host, addr) < 0)
  580.             return 0;
  581.         addr->sin_family = AF_INET;
  582.         addr->sin_port = htons((short)port);
  583.         *addr_ret = (struct sockaddr *) addr;
  584.         *len_ret = sizeof *addr;
  585.         return 1;
  586.     }
  587.  
  588.     /* More cases here... */
  589.  
  590.     default:
  591.         PyErr_SetString(PySocket_Error, "getsockaddrarg: bad family");
  592.         return 0;
  593.  
  594.     }
  595. }
  596.  
  597.  
  598. /* Get the address length according to the socket object's address family. 
  599.    Return 1 if the family is known, 0 otherwise.  The length is returned
  600.    through len_ret. */
  601.  
  602. static int
  603. BUILD_FUNC_DEF_2(getsockaddrlen,PySocketSockObject *,s, int *,len_ret)
  604. {
  605.     switch (s->sock_family) {
  606.  
  607. #ifdef AF_UNIX
  608.     case AF_UNIX:
  609.     {
  610.         *len_ret = sizeof (struct sockaddr_un);
  611.         return 1;
  612.     }
  613. #endif /* AF_UNIX */
  614.  
  615.     case AF_INET:
  616.     {
  617.         *len_ret = sizeof (struct sockaddr_in);
  618.         return 1;
  619.     }
  620.  
  621.     /* More cases here... */
  622.  
  623.     default:
  624.         PyErr_SetString(PySocket_Error, "getsockaddrarg: bad family");
  625.         return 0;
  626.  
  627.     }
  628. }
  629.  
  630.  
  631. /* s.accept() method */
  632.  
  633. static PyObject *
  634. BUILD_FUNC_DEF_2(PySocketSock_accept,PySocketSockObject *,s, PyObject *,args)
  635. {
  636.     char addrbuf[256];
  637.     int addrlen, newfd;
  638.     PyObject *sock = NULL;
  639.     PyObject *addr = NULL;
  640.     PyObject *res = NULL;
  641.  
  642.     if (!PyArg_NoArgs(args))
  643.         return NULL;
  644.     if (!getsockaddrlen(s, &addrlen))
  645.         return NULL;
  646.     Py_BEGIN_ALLOW_THREADS
  647.     newfd = accept(s->sock_fd, (struct sockaddr *) addrbuf, &addrlen);
  648.     Py_END_ALLOW_THREADS
  649.     if (newfd < 0)
  650.         return PySocket_Err();
  651.  
  652.     /* Create the new object with unspecified family,
  653.        to avoid calls to bind() etc. on it. */
  654.     sock = (PyObject *) PySocketSock_New(newfd,
  655.                     s->sock_family,
  656.                     s->sock_type,
  657.                     s->sock_proto);
  658.     if (sock == NULL) {
  659.         close(newfd);
  660.         goto finally;
  661.     }
  662.     if (!(addr = makesockaddr((struct sockaddr *) addrbuf, addrlen)))
  663.         goto finally;
  664.  
  665.     if (!(res = Py_BuildValue("OO", sock, addr)))
  666.         goto finally;
  667.  
  668.   finally:
  669.     Py_XDECREF(sock);
  670.     Py_XDECREF(addr);
  671.     return res;
  672. }
  673.  
  674. static char accept_doc[] =
  675. "accept() -> (socket object, address info)\n\
  676. \n\
  677. Wait for an incoming connection.  Return a new socket representing the\n\
  678. connection, and the address of the client.  For IP sockets, the address\n\
  679. info is a pair (hostaddr, port).";
  680.  
  681.  
  682. /* s.setblocking(1 | 0) method */
  683.  
  684. static PyObject *
  685. BUILD_FUNC_DEF_2(PySocketSock_setblocking,PySocketSockObject*,s,PyObject*,args)
  686. {
  687.     int block;
  688. #ifndef MS_WINDOWS
  689.     int delay_flag;
  690. #endif
  691.     if (!PyArg_Parse(args, "i", &block))
  692.         return NULL;
  693.     Py_BEGIN_ALLOW_THREADS
  694. #ifdef __BEOS__
  695.     block = !block;
  696.     setsockopt( s->sock_fd, SOL_SOCKET, SO_NONBLOCK,
  697.                 (void *)(&block), sizeof( int ) );
  698. #else
  699. #ifndef MS_WINDOWS
  700. #ifdef PYOS_OS2
  701.     block = !block;
  702.     ioctl(s->sock_fd, FIONBIO, (caddr_t)&block, sizeof(block));
  703. #else /* !PYOS_OS2 */
  704.  #if defined(AMITCP) || defined (INET225)
  705.     block = !block;
  706.     ioctlsocket(s->sock_fd, FIONBIO, &block);
  707.  #else
  708.     delay_flag = fcntl (s->sock_fd, F_GETFL, 0);
  709.     if (block)
  710.         delay_flag &= (~O_NDELAY);
  711.     else
  712.         delay_flag |= O_NDELAY;
  713.     fcntl (s->sock_fd, F_SETFL, delay_flag);
  714.  #endif /* !AMITCP || INET225 */
  715. #endif /* !PYOS_OS2 */
  716. #else /* MS_WINDOWS */
  717.     block = !block;
  718.     ioctlsocket(s->sock_fd, FIONBIO, (u_long*)&block);
  719. #endif /* MS_WINDOWS */
  720. #endif /* __BEOS__ */
  721.     Py_END_ALLOW_THREADS
  722.  
  723.     Py_INCREF(Py_None);
  724.     return Py_None;
  725. }
  726.  
  727. static char setblocking_doc[] =
  728. "setblocking(flag)\n\
  729. \n\
  730. Set the socket to blocking (flag is true) or non-blocking (false).\n\
  731. This uses the FIONBIO ioctl with the O_NDELAY flag.";
  732.  
  733.  
  734. /* s.setsockopt() method.
  735.    With an integer third argument, sets an integer option.
  736.    With a string third argument, sets an option from a buffer;
  737.    use optional built-in module 'struct' to encode the string. */
  738.  
  739. static PyObject *
  740. BUILD_FUNC_DEF_2(PySocketSock_setsockopt,PySocketSockObject *,s, PyObject *,args)
  741. {
  742.     int level;
  743.     int optname;
  744.     int res;
  745.     char *buf;
  746.     int buflen;
  747.     int flag;
  748.  
  749.     if (PyArg_Parse(args, "(iii)", &level, &optname, &flag)) {
  750.         buf = (char *) &flag;
  751.         buflen = sizeof flag;
  752.     }
  753.     else {
  754.         PyErr_Clear();
  755.         if (!PyArg_Parse(args, "(iis#)", &level, &optname,
  756.                  &buf, &buflen))
  757.             return NULL;
  758.     }
  759.     res = setsockopt(s->sock_fd, level, optname, (ANY *)buf, buflen);
  760.     if (res < 0)
  761.         return PySocket_Err();
  762.     Py_INCREF(Py_None);
  763.     return Py_None;
  764. }
  765.  
  766. static char setsockopt_doc[] =
  767. "setsockopt(level, option, value)\n\
  768. \n\
  769. Set a socket option.  See the Unix manual for level and option.\n\
  770. The value argument can either be an integer or a string.";
  771.  
  772.  
  773. /* s.getsockopt() method.
  774.    With two arguments, retrieves an integer option.
  775.    With a third integer argument, retrieves a string buffer of that size;
  776.    use optional built-in module 'struct' to decode the string. */
  777.  
  778. static PyObject *
  779. BUILD_FUNC_DEF_2(PySocketSock_getsockopt,PySocketSockObject *,s, PyObject *,args)
  780. {
  781.     int level;
  782.     int optname;
  783.     int res;
  784.     PyObject *buf;
  785.     int buflen = 0;
  786.  
  787. #ifdef __BEOS__
  788. /* We have incomplete socket support. */
  789.     PyErr_SetString( PySocket_Error, "getsockopt not supported" );
  790.     return NULL;
  791. #else
  792.  
  793.     if (!PyArg_ParseTuple(args, "ii|i", &level, &optname, &buflen))
  794.         return NULL;
  795.     
  796.     if (buflen == 0) {
  797.         int flag = 0;
  798.         int flagsize = sizeof flag;
  799.         res = getsockopt(s->sock_fd, level, optname,
  800.                  (ANY *)&flag, &flagsize);
  801.         if (res < 0)
  802.             return PySocket_Err();
  803.         return PyInt_FromLong(flag);
  804.     }
  805.     if (buflen <= 0 || buflen > 1024) {
  806.         PyErr_SetString(PySocket_Error,
  807.                 "getsockopt buflen out of range");
  808.         return NULL;
  809.     }
  810.     buf = PyString_FromStringAndSize((char *)NULL, buflen);
  811.     if (buf == NULL)
  812.         return NULL;
  813.     res = getsockopt(s->sock_fd, level, optname,
  814.              (ANY *)PyString_AsString(buf), &buflen);
  815.     if (res < 0) {
  816.         Py_DECREF(buf);
  817.         return PySocket_Err();
  818.     }
  819.     _PyString_Resize(&buf, buflen);
  820.     return buf;
  821. #endif /* __BEOS__ */
  822. }
  823.  
  824. static char getsockopt_doc[] =
  825. "getsockopt(level, option[, buffersize]) -> value\n\
  826. \n\
  827. Get a socket option.  See the Unix manual for level and option.\n\
  828. If a nonzero buffersize argument is given, the return value is a\n\
  829. string of that length; otherwise it is an integer.";
  830.  
  831.  
  832. /* s.bind(sockaddr) method */
  833.  
  834. static PyObject *
  835. BUILD_FUNC_DEF_2(PySocketSock_bind,PySocketSockObject *,s, PyObject *,args)
  836. {
  837.     struct sockaddr *addr;
  838.     int addrlen;
  839.     int res;
  840.     if (!getsockaddrarg(s, args, &addr, &addrlen))
  841.         return NULL;
  842.     Py_BEGIN_ALLOW_THREADS
  843.     res = bind(s->sock_fd, addr, addrlen);
  844.     Py_END_ALLOW_THREADS
  845.     if (res < 0)
  846.         return PySocket_Err();
  847.     Py_INCREF(Py_None);
  848.     return Py_None;
  849. }
  850.  
  851. static char bind_doc[] =
  852. "bind(address)\n\
  853. \n\
  854. Bind the socket to a local address.  For IP sockets, the address is a\n\
  855. pair (host, port); the host must refer to the local host.";
  856.  
  857.  
  858. /* s.close() method.
  859.    Set the file descriptor to -1 so operations tried subsequently
  860.    will surely fail. */
  861.  
  862. static PyObject *
  863. BUILD_FUNC_DEF_2(PySocketSock_close,PySocketSockObject *,s, PyObject *,args)
  864. {
  865.     if (!PyArg_NoArgs(args))
  866.         return NULL;
  867.     if (s->sock_fd != -1) {
  868.         Py_BEGIN_ALLOW_THREADS
  869.         (void) close(s->sock_fd);
  870.         Py_END_ALLOW_THREADS
  871.     }
  872.     s->sock_fd = -1;
  873.     Py_INCREF(Py_None);
  874.     return Py_None;
  875. }
  876.  
  877. static char close_doc[] =
  878. "close()\n\
  879. \n\
  880. Close the socket.  It cannot be used after this call.";
  881.  
  882.  
  883. /* s.connect(sockaddr) method */
  884.  
  885. static PyObject *
  886. BUILD_FUNC_DEF_2(PySocketSock_connect,PySocketSockObject *,s, PyObject *,args)
  887. {
  888.     struct sockaddr *addr;
  889.     int addrlen;
  890.     int res;
  891.     if (!getsockaddrarg(s, args, &addr, &addrlen))
  892.         return NULL;
  893.     Py_BEGIN_ALLOW_THREADS
  894.     res = connect(s->sock_fd, addr, addrlen);
  895.     Py_END_ALLOW_THREADS
  896.     if (res < 0)
  897.         return PySocket_Err();
  898.     Py_INCREF(Py_None);
  899.     return Py_None;
  900. }
  901.  
  902. static char connect_doc[] =
  903. "connect(address)\n\
  904. \n\
  905. Connect the socket to a remote address.  For IP sockets, the address\n\
  906. is a pair (host, port).";
  907.  
  908.  
  909. /* s.connect_ex(sockaddr) method */
  910.  
  911. static PyObject *
  912. BUILD_FUNC_DEF_2(PySocketSock_connect_ex,PySocketSockObject *,s, PyObject *,args)
  913. {
  914.     struct sockaddr *addr;
  915.     int addrlen;
  916.     int res;
  917.     if (!getsockaddrarg(s, args, &addr, &addrlen))
  918.         return NULL;
  919.     Py_BEGIN_ALLOW_THREADS
  920.     res = connect(s->sock_fd, addr, addrlen);
  921.     Py_END_ALLOW_THREADS
  922.     if (res != 0)
  923.         res = errno;
  924.     return PyInt_FromLong((long) res);
  925. }
  926.  
  927. static char connect_ex_doc[] =
  928. "connect_ex(address)\n\
  929. \n\
  930. This is like connect(address), but returns an error code (the errno value)\n\
  931. instead of raising an exception when an error occurs.";
  932.  
  933.  
  934. /* s.fileno() method */
  935.  
  936. static PyObject *
  937. BUILD_FUNC_DEF_2(PySocketSock_fileno,PySocketSockObject *,s, PyObject *,args)
  938. {
  939.     if (!PyArg_NoArgs(args))
  940.         return NULL;
  941.     return PyInt_FromLong((long) s->sock_fd);
  942. }
  943.  
  944. static char fileno_doc[] =
  945. "fileno() -> integer\n\
  946. \n\
  947. Return the integer file descriptor of the socket.";
  948.  
  949.  
  950. #ifndef NO_DUP
  951. /* s.dup() method */
  952.  
  953. static PyObject *
  954. BUILD_FUNC_DEF_2(PySocketSock_dup,PySocketSockObject *,s, PyObject *,args)
  955. {
  956.     int newfd;
  957.     PyObject *sock;
  958.     if (!PyArg_NoArgs(args))
  959.         return NULL;
  960.     newfd = dup(s->sock_fd);
  961.     if (newfd < 0)
  962.         return PySocket_Err();
  963.     sock = (PyObject *) PySocketSock_New(newfd,
  964.                          s->sock_family,
  965.                          s->sock_type,
  966.                          s->sock_proto);
  967.     if (sock == NULL)
  968.         close(newfd);
  969.     return sock;
  970. }
  971.  
  972. static char dup_doc[] =
  973. "dup() -> socket object\n\
  974. \n\
  975. Return a new socket object connected to the same system resource.";
  976.  
  977. #endif
  978.  
  979.  
  980. /* s.getsockname() method */
  981.  
  982. static PyObject *
  983. BUILD_FUNC_DEF_2(PySocketSock_getsockname,PySocketSockObject *,s, PyObject *,args)
  984. {
  985.     char addrbuf[256];
  986.     int addrlen, res;
  987.     if (!PyArg_NoArgs(args))
  988.         return NULL;
  989.     if (!getsockaddrlen(s, &addrlen))
  990.         return NULL;
  991.     memset(addrbuf, 0, addrlen);
  992.     Py_BEGIN_ALLOW_THREADS
  993.     res = getsockname(s->sock_fd, (struct sockaddr *) addrbuf, &addrlen);
  994.     Py_END_ALLOW_THREADS
  995.     if (res < 0)
  996.         return PySocket_Err();
  997.     return makesockaddr((struct sockaddr *) addrbuf, addrlen);
  998. }
  999.  
  1000. static char getsockname_doc[] =
  1001. "getsockname() -> address info\n\
  1002. \n\
  1003. Return the address of the local endpoint.  For IP sockets, the address\n\
  1004. info is a pair (hostaddr, port).";
  1005.  
  1006.  
  1007. #ifdef HAVE_GETPEERNAME        /* Cray APP doesn't have this :-( */
  1008. /* s.getpeername() method */
  1009.  
  1010. static PyObject *
  1011. BUILD_FUNC_DEF_2(PySocketSock_getpeername,PySocketSockObject *,s, PyObject *,args)
  1012. {
  1013.     char addrbuf[256];
  1014.     int addrlen, res;
  1015.     if (!PyArg_NoArgs(args))
  1016.         return NULL;
  1017.     if (!getsockaddrlen(s, &addrlen))
  1018.         return NULL;
  1019.     Py_BEGIN_ALLOW_THREADS
  1020.     res = getpeername(s->sock_fd, (struct sockaddr *) addrbuf, &addrlen);
  1021.     Py_END_ALLOW_THREADS
  1022.     if (res < 0)
  1023.         return PySocket_Err();
  1024.     return makesockaddr((struct sockaddr *) addrbuf, addrlen);
  1025. }
  1026.  
  1027. static char getpeername_doc[] =
  1028. "getpeername() -> address info\n\
  1029. \n\
  1030. Return the address of the remote endpoint.  For IP sockets, the address\n\
  1031. info is a pair (hostaddr, port).";
  1032.  
  1033. #endif /* HAVE_GETPEERNAME */
  1034.  
  1035.  
  1036. /* s.listen(n) method */
  1037.  
  1038. static PyObject *
  1039. BUILD_FUNC_DEF_2(PySocketSock_listen,PySocketSockObject *,s, PyObject *,args)
  1040. {
  1041.     int backlog;
  1042.     int res;
  1043.     if (!PyArg_Parse(args, "i", &backlog))
  1044.         return NULL;
  1045.     Py_BEGIN_ALLOW_THREADS
  1046.     if (backlog < 1)
  1047.         backlog = 1;
  1048.     res = listen(s->sock_fd, backlog);
  1049.     Py_END_ALLOW_THREADS
  1050.     if (res < 0)
  1051.         return PySocket_Err();
  1052.     Py_INCREF(Py_None);
  1053.     return Py_None;
  1054. }
  1055.  
  1056. static char listen_doc[] =
  1057. "listen(backlog)\n\
  1058. \n\
  1059. Enable a server to accept connections.  The backlog argument must be at\n\
  1060. least 1; it specifies the number of unaccepted connection that the system\n\
  1061. will allow before refusing new connections.";
  1062.  
  1063.  
  1064. #ifndef NO_DUP
  1065. /* s.makefile(mode) method.
  1066.    Create a new open file object referring to a dupped version of
  1067.    the socket's file descriptor.  (The dup() call is necessary so
  1068.    that the open file and socket objects may be closed independent
  1069.    of each other.)
  1070.    The mode argument specifies 'r' or 'w' passed to fdopen(). */
  1071.  
  1072. static PyObject *
  1073. BUILD_FUNC_DEF_2(PySocketSock_makefile,PySocketSockObject *,s, PyObject *,args)
  1074. {
  1075.     extern int fclose Py_PROTO((FILE *));
  1076.     char *mode = "r";
  1077.     int bufsize = -1;
  1078.     int fd;
  1079.     FILE *fp;
  1080.     PyObject *f;
  1081.  
  1082.     if (!PyArg_ParseTuple(args, "|si", &mode, &bufsize))
  1083.         return NULL;
  1084. #ifdef MS_WIN32
  1085.     if (((fd = _open_osfhandle(s->sock_fd, _O_BINARY)) < 0) ||
  1086.         ((fd = dup(fd)) < 0) || ((fp = fdopen(fd, mode)) == NULL))
  1087. #else
  1088.     if ((fd = dup(s->sock_fd)) < 0 || (fp = fdopen(fd, mode)) == NULL)
  1089. #endif
  1090.     {
  1091.         if (fd >= 0)
  1092.             close(fd);
  1093.         return PySocket_Err();
  1094.     }
  1095.     f = PyFile_FromFile(fp, "<socket>", mode, fclose);
  1096.     if (f != NULL)
  1097.         PyFile_SetBufSize(f, bufsize);
  1098.     return f;
  1099. }
  1100.  
  1101. static char makefile_doc[] =
  1102. "makefile([mode[, buffersize]]) -> file object\n\
  1103. \n\
  1104. Return a regular file object corresponding to the socket.\n\
  1105. The mode and buffersize arguments are as for the built-in open() function.";
  1106.  
  1107. #endif /* NO_DUP */
  1108.  
  1109.  
  1110. /* s.recv(nbytes [,flags]) method */
  1111.  
  1112. static PyObject *
  1113. BUILD_FUNC_DEF_2(PySocketSock_recv,PySocketSockObject *,s, PyObject *,args)
  1114. {
  1115.     int len, n, flags = 0;
  1116.     PyObject *buf;
  1117.     if (!PyArg_ParseTuple(args, "i|i", &len, &flags))
  1118.         return NULL;
  1119.     buf = PyString_FromStringAndSize((char *) 0, len);
  1120.     if (buf == NULL)
  1121.         return NULL;
  1122.     Py_BEGIN_ALLOW_THREADS
  1123.     n = recv(s->sock_fd, PyString_AsString(buf), len, flags);
  1124.     Py_END_ALLOW_THREADS
  1125.     if (n < 0) {
  1126.         Py_DECREF(buf);
  1127.         return PySocket_Err();
  1128.     }
  1129.     if (n != len && _PyString_Resize(&buf, n) < 0)
  1130.         return NULL;
  1131.     return buf;
  1132. }
  1133.  
  1134. static char recv_doc[] =
  1135. "recv(buffersize[, flags]) -> data\n\
  1136. \n\
  1137. Receive up to buffersize bytes from the socket.  For the optional flags\n\
  1138. argument, see the Unix manual.  When no data is available, block until\n\
  1139. at least one byte is available or until the remote end is closed.  When\n\
  1140. the remote end is closed and all data is read, return the empty string.";
  1141.  
  1142.  
  1143. /* s.recvfrom(nbytes [,flags]) method */
  1144.  
  1145. static PyObject *
  1146. BUILD_FUNC_DEF_2(PySocketSock_recvfrom,PySocketSockObject *,s, PyObject *,args)
  1147. {
  1148.     char addrbuf[256];
  1149.     PyObject *buf = NULL;
  1150.     PyObject *addr = NULL;
  1151.     PyObject *ret = NULL;
  1152.  
  1153.     int addrlen, len, n, flags = 0;
  1154.     if (!PyArg_ParseTuple(args, "i|i", &len, &flags))
  1155.         return NULL;
  1156.     if (!getsockaddrlen(s, &addrlen))
  1157.         return NULL;
  1158.     buf = PyString_FromStringAndSize((char *) 0, len);
  1159.     if (buf == NULL)
  1160.         return NULL;
  1161.     Py_BEGIN_ALLOW_THREADS
  1162.     n = recvfrom(s->sock_fd, PyString_AsString(buf), len, flags,
  1163. #ifndef MS_WINDOWS
  1164. #if defined(PYOS_OS2)
  1165.              (struct sockaddr *)addrbuf, &addrlen
  1166. #else
  1167.              (ANY *)addrbuf, &addrlen
  1168. #endif
  1169. #else
  1170.              (struct sockaddr *)addrbuf, &addrlen
  1171. #endif
  1172.              );
  1173.     Py_END_ALLOW_THREADS
  1174.     if (n < 0) {
  1175.         Py_DECREF(buf);
  1176.         return PySocket_Err();
  1177.     }
  1178.     if (n != len && _PyString_Resize(&buf, n) < 0)
  1179.         return NULL;
  1180.         
  1181.     if (!(addr = makesockaddr((struct sockaddr *)addrbuf, addrlen)))
  1182.         goto finally;
  1183.  
  1184.     ret = Py_BuildValue("OO", buf, addr);
  1185.   finally:
  1186.     Py_XDECREF(addr);
  1187.     Py_XDECREF(buf);
  1188.     return ret;
  1189. }
  1190.  
  1191. static char recvfrom_doc[] =
  1192. "recvfrom(buffersize[, flags]) -> (data, address info)\n\
  1193. \n\
  1194. Like recv(buffersize, flags) but also return the sender's address info.";
  1195.  
  1196.  
  1197. /* s.send(data [,flags]) method */
  1198.  
  1199. static PyObject *
  1200. BUILD_FUNC_DEF_2(PySocketSock_send,PySocketSockObject *,s, PyObject *,args)
  1201. {
  1202.     char *buf;
  1203.     int len, n, flags = 0;
  1204.     if (!PyArg_ParseTuple(args, "s#|i", &buf, &len, &flags))
  1205.         return NULL;
  1206.     Py_BEGIN_ALLOW_THREADS
  1207.     n = send(s->sock_fd, buf, len, flags);
  1208.     Py_END_ALLOW_THREADS
  1209.     if (n < 0)
  1210.         return PySocket_Err();
  1211.     return PyInt_FromLong((long)n);
  1212. }
  1213.  
  1214. static char send_doc[] =
  1215. "send(data[, flags])\n\
  1216. \n\
  1217. Send a data string to the socket.  For the optional flags\n\
  1218. argument, see the Unix manual.";
  1219.  
  1220.  
  1221. /* s.sendto(data, [flags,] sockaddr) method */
  1222.  
  1223. static PyObject *
  1224. BUILD_FUNC_DEF_2(PySocketSock_sendto,PySocketSockObject *,s, PyObject *,args)
  1225. {
  1226.     PyObject *addro;
  1227.     char *buf;
  1228.     struct sockaddr *addr;
  1229.     int addrlen, len, n, flags;
  1230.     flags = 0;
  1231.     if (!PyArg_Parse(args, "(s#O)", &buf, &len, &addro)) {
  1232.         PyErr_Clear();
  1233.         if (!PyArg_Parse(args, "(s#iO)", &buf, &len, &flags, &addro))
  1234.             return NULL;
  1235.     }
  1236.     if (!getsockaddrarg(s, addro, &addr, &addrlen))
  1237.         return NULL;
  1238.     Py_BEGIN_ALLOW_THREADS
  1239.     n = sendto(s->sock_fd, buf, len, flags, addr, addrlen);
  1240.     Py_END_ALLOW_THREADS
  1241.     if (n < 0)
  1242.         return PySocket_Err();
  1243.     return PyInt_FromLong((long)n);
  1244. }
  1245.  
  1246. static char sendto_doc[] =
  1247. "sendto(data[, flags], address)\n\
  1248. \n\
  1249. Like send(data, flags) but allows specifying the destination address.\n\
  1250. For IP sockets, the address is a pair (hostaddr, port).";
  1251.  
  1252.  
  1253. /* s.shutdown(how) method */
  1254.  
  1255. static PyObject *
  1256. BUILD_FUNC_DEF_2(PySocketSock_shutdown,PySocketSockObject *,s, PyObject *,args)
  1257. {
  1258.     int how;
  1259.     int res;
  1260.     if (!PyArg_Parse(args, "i", &how))
  1261.         return NULL;
  1262.     Py_BEGIN_ALLOW_THREADS
  1263.     res = shutdown(s->sock_fd, how);
  1264.     Py_END_ALLOW_THREADS
  1265.     if (res < 0)
  1266.         return PySocket_Err();
  1267.     Py_INCREF(Py_None);
  1268.     return Py_None;
  1269. }
  1270.  
  1271. static char shutdown_doc[] =
  1272. "shutdown(flag)\n\
  1273. \n\
  1274. Shut down the reading side of the socket (flag == 0), the writing side\n\
  1275. of the socket (flag == 1), or both ends (flag == 2).";
  1276.  
  1277.  
  1278. /* List of methods for socket objects */
  1279.  
  1280. static PyMethodDef PySocketSock_methods[] = {
  1281.     {"accept",        (PyCFunction)PySocketSock_accept, 0,
  1282.                 accept_doc},
  1283.     {"bind",        (PyCFunction)PySocketSock_bind, 0,
  1284.                 bind_doc},
  1285.     {"close",        (PyCFunction)PySocketSock_close, 0,
  1286.                 close_doc},
  1287.     {"connect",        (PyCFunction)PySocketSock_connect, 0,
  1288.                 connect_doc},
  1289.     {"connect_ex",        (PyCFunction)PySocketSock_connect_ex, 0,
  1290.                 connect_ex_doc},
  1291. #ifndef NO_DUP
  1292.     {"dup",            (PyCFunction)PySocketSock_dup, 0,
  1293.                 dup_doc},
  1294. #endif
  1295.     {"fileno",        (PyCFunction)PySocketSock_fileno, 0,
  1296.                 fileno_doc},
  1297. #ifdef HAVE_GETPEERNAME
  1298.     {"getpeername",        (PyCFunction)PySocketSock_getpeername, 0,
  1299.                 getpeername_doc},
  1300. #endif
  1301.     {"getsockname",        (PyCFunction)PySocketSock_getsockname, 0,
  1302.                 getsockname_doc},
  1303.     {"getsockopt",        (PyCFunction)PySocketSock_getsockopt, 1,
  1304.                 getsockopt_doc},
  1305.     {"listen",        (PyCFunction)PySocketSock_listen, 0,
  1306.                 listen_doc},
  1307. #ifndef NO_DUP
  1308.     {"makefile",        (PyCFunction)PySocketSock_makefile, 1,
  1309.                 makefile_doc},
  1310. #endif
  1311.     {"recv",        (PyCFunction)PySocketSock_recv, 1,
  1312.                 recv_doc},
  1313.     {"recvfrom",        (PyCFunction)PySocketSock_recvfrom, 1,
  1314.                 recvfrom_doc},
  1315.     {"send",        (PyCFunction)PySocketSock_send, 1,
  1316.                 send_doc},
  1317.     {"sendto",        (PyCFunction)PySocketSock_sendto, 0,
  1318.                 sendto_doc},
  1319.     {"setblocking",        (PyCFunction)PySocketSock_setblocking, 0,
  1320.                 setblocking_doc},
  1321.     {"setsockopt",        (PyCFunction)PySocketSock_setsockopt, 0,
  1322.                 setsockopt_doc},
  1323.     {"shutdown",        (PyCFunction)PySocketSock_shutdown, 0,
  1324.                 shutdown_doc},
  1325.     {NULL,            NULL}        /* sentinel */
  1326. };
  1327.  
  1328.  
  1329. /* Deallocate a socket object in response to the last Py_DECREF().
  1330.    First close the file description. */
  1331.  
  1332. static void
  1333. BUILD_FUNC_DEF_1(PySocketSock_dealloc,PySocketSockObject *,s)
  1334. {
  1335.     (void) close(s->sock_fd);
  1336.     PyMem_DEL(s);
  1337. }
  1338.  
  1339.  
  1340. /* Return a socket object's named attribute. */
  1341.  
  1342. static PyObject *
  1343. BUILD_FUNC_DEF_2(PySocketSock_getattr,PySocketSockObject *,s, char *,name)
  1344. {
  1345.     return Py_FindMethod(PySocketSock_methods, (PyObject *) s, name);
  1346. }
  1347.  
  1348.  
  1349. static PyObject *
  1350. BUILD_FUNC_DEF_1(PySocketSock_repr,PySocketSockObject *,s)
  1351. {
  1352.     char buf[512];
  1353.     sprintf(buf, 
  1354.         "<socket object, fd=%d, family=%d, type=%d, protocol=%d>", 
  1355.         s->sock_fd, s->sock_family, s->sock_type, s->sock_proto);
  1356.     return PyString_FromString(buf);
  1357. }
  1358.  
  1359.  
  1360. /* Type object for socket objects. */
  1361.  
  1362. static PyTypeObject PySocketSock_Type = {
  1363.     PyObject_HEAD_INIT(0)    /* Must fill in type value later */
  1364.     0,
  1365.     "socket",
  1366.     sizeof(PySocketSockObject),
  1367.     0,
  1368.     (destructor)PySocketSock_dealloc, /*tp_dealloc*/
  1369.     0,        /*tp_print*/
  1370.     (getattrfunc)PySocketSock_getattr, /*tp_getattr*/
  1371.     0,        /*tp_setattr*/
  1372.     0,        /*tp_compare*/
  1373.     (reprfunc)PySocketSock_repr, /*tp_repr*/
  1374.     0,        /*tp_as_number*/
  1375.     0,        /*tp_as_sequence*/
  1376.     0,        /*tp_as_mapping*/
  1377. };
  1378.  
  1379.  
  1380. /* Python interface to gethostname(). */
  1381.  
  1382. /*ARGSUSED*/
  1383. static PyObject *
  1384. BUILD_FUNC_DEF_2(PySocket_gethostname,PyObject *,self, PyObject *,args)
  1385. {
  1386.     char buf[1024];
  1387.     int res;
  1388.     if (!PyArg_NoArgs(args))
  1389.         return NULL;
  1390.     Py_BEGIN_ALLOW_THREADS
  1391.     res = gethostname(buf, (int) sizeof buf - 1);
  1392.     Py_END_ALLOW_THREADS
  1393.     if (res < 0)
  1394.         return PySocket_Err();
  1395.     buf[sizeof buf - 1] = '\0';
  1396.     return PyString_FromString(buf);
  1397. }
  1398.  
  1399. static char gethostname_doc[] =
  1400. "gethostname() -> string\n\
  1401. \n\
  1402. Return the current host name.";
  1403.  
  1404.  
  1405. /* Python interface to gethostbyname(name). */
  1406.  
  1407. /*ARGSUSED*/
  1408. static PyObject *
  1409. BUILD_FUNC_DEF_2(PySocket_gethostbyname,PyObject *,self, PyObject *,args)
  1410. {
  1411.     char *name;
  1412.     struct sockaddr_in addrbuf;
  1413.     if (!PyArg_Parse(args, "s", &name))
  1414.         return NULL;
  1415.     if (setipaddr(name, &addrbuf) < 0)
  1416.         return NULL;
  1417.     return makeipaddr(&addrbuf);
  1418. }
  1419.  
  1420. static char gethostbyname_doc[] =
  1421. "gethostbyname(host) -> address\n\
  1422. \n\
  1423. Return the IP address (a string of the form '255.255.255.255') for a host.";
  1424.  
  1425.  
  1426. /* Convenience function common to gethostbyname_ex and gethostbyaddr */
  1427.  
  1428. static PyObject *
  1429. gethost_common(h, addr)
  1430.     struct hostent *h;
  1431.     struct sockaddr_in *addr;
  1432. {
  1433.     char **pch;
  1434.     PyObject *rtn_tuple = (PyObject *)NULL;
  1435.     PyObject *name_list = (PyObject *)NULL;
  1436.     PyObject *addr_list = (PyObject *)NULL;
  1437.     PyObject *tmp;
  1438.     if (h == NULL) {
  1439. #ifdef HAVE_HSTRERROR
  1440.             /* Let's get real error message to return */
  1441.             extern int h_errno;
  1442.         PyErr_SetString(PySocket_Error, (char *)hstrerror(h_errno));
  1443. #else
  1444.         PyErr_SetString(PySocket_Error, "host not found");
  1445. #endif
  1446.         return NULL;
  1447.     }
  1448.     if ((name_list = PyList_New(0)) == NULL)
  1449.         goto err;
  1450.     if ((addr_list = PyList_New(0)) == NULL)
  1451.         goto err;
  1452.     for (pch = h->h_aliases; *pch != NULL; pch++) {
  1453.         int status;
  1454.         tmp = PyString_FromString(*pch);
  1455.         if (tmp == NULL)
  1456.             goto err;
  1457.         status = PyList_Append(name_list, tmp);
  1458.         Py_DECREF(tmp);
  1459.         if (status)
  1460.             goto err;
  1461.     }
  1462.     for (pch = h->h_addr_list; *pch != NULL; pch++) {
  1463.         int status;
  1464.         memcpy((char *) &addr->sin_addr, *pch, h->h_length);
  1465.         tmp = makeipaddr(addr);
  1466.         if (tmp == NULL)
  1467.             goto err;
  1468.         status = PyList_Append(addr_list, tmp);
  1469.         Py_DECREF(tmp);
  1470.         if (status)
  1471.             goto err;
  1472.     }
  1473.     rtn_tuple = Py_BuildValue("sOO", h->h_name, name_list, addr_list);
  1474.  err:
  1475.     Py_XDECREF(name_list);
  1476.     Py_XDECREF(addr_list);
  1477.     return rtn_tuple;
  1478. }
  1479.  
  1480.  
  1481. /* Python interface to gethostbyname_ex(name). */
  1482.  
  1483. /*ARGSUSED*/
  1484. static PyObject *
  1485. BUILD_FUNC_DEF_2(PySocket_gethostbyname_ex,PyObject *,self, PyObject *,args)
  1486. {
  1487.     char *name;
  1488.     struct hostent *h;
  1489.     struct sockaddr_in addr;
  1490.     PyObject *ret;
  1491. #ifdef HAVE_GETHOSTBYNAME_R
  1492.     struct hostent hp_allocated;
  1493. #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
  1494.     struct hostent_data data;
  1495. #else
  1496.     char buf[16384];
  1497.     int buf_len = (sizeof buf) - 1;
  1498.     int errnop;
  1499. #endif
  1500. #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
  1501.     int result;
  1502. #endif
  1503. #endif /* HAVE_GETHOSTBYNAME_R */
  1504.     if (!PyArg_Parse(args, "s", &name))
  1505.         return NULL;
  1506.     if (setipaddr(name, &addr) < 0)
  1507.         return NULL;
  1508.     Py_BEGIN_ALLOW_THREADS
  1509. #ifdef HAVE_GETHOSTBYNAME_R
  1510. #if   defined(HAVE_GETHOSTBYNAME_R_6_ARG)
  1511.     result = gethostbyname_r(name, &hp_allocated, buf, buf_len, &h, &errnop);
  1512. #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
  1513.     h = gethostbyname_r(name, &hp_allocated, buf, buf_len, &errnop);
  1514. #else /* HAVE_GETHOSTBYNAME_R_3_ARG */
  1515.     memset((void *) &data, '\0', sizeof(data));
  1516.     result = gethostbyname_r(name, &hp_allocated, &data);
  1517.     h = (result != 0) ? NULL : &hp_allocated;
  1518. #endif
  1519. #else /* not HAVE_GETHOSTBYNAME_R */
  1520. #ifdef USE_GETHOSTBYNAME_LOCK
  1521.     PyThread_acquire_lock(gethostbyname_lock, 1);
  1522. #endif
  1523.     h = gethostbyname(name);
  1524. #endif /* HAVE_GETHOSTBYNAME_R */
  1525.     Py_END_ALLOW_THREADS
  1526.     ret = gethost_common(h, &addr);
  1527. #ifdef USE_GETHOSTBYNAME_LOCK
  1528.     PyThread_release_lock(gethostbyname_lock);
  1529. #endif
  1530.     return ret;
  1531. }
  1532.  
  1533. static char ghbn_ex_doc[] =
  1534. "gethostbyname_ex(host) -> (name, aliaslist, addresslist)\n\
  1535. \n\
  1536. Return the true host name, a list of aliases, and a list of IP addresses,\n\
  1537. for a host.  The host argument is a string giving a host name or IP number.";
  1538.  
  1539.  
  1540. /* Python interface to gethostbyaddr(IP). */
  1541.  
  1542. /*ARGSUSED*/
  1543. static PyObject *
  1544. BUILD_FUNC_DEF_2(PySocket_gethostbyaddr,PyObject *,self, PyObject *, args)
  1545. {
  1546.         struct sockaddr_in addr;
  1547.     char *ip_num;
  1548.     struct hostent *h;
  1549.     PyObject *ret;
  1550. #ifdef HAVE_GETHOSTBYNAME_R
  1551.     struct hostent hp_allocated;
  1552. #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
  1553.     struct hostent_data data;
  1554. #else
  1555.     char buf[16384];
  1556.     int buf_len = (sizeof buf) - 1;
  1557.     int errnop;
  1558. #endif
  1559. #if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
  1560.     int result;
  1561. #endif
  1562. #endif /* HAVE_GETHOSTBYNAME_R */
  1563.  
  1564.     if (!PyArg_Parse(args, "s", &ip_num))
  1565.         return NULL;
  1566.     if (setipaddr(ip_num, &addr) < 0)
  1567.         return NULL;
  1568.     Py_BEGIN_ALLOW_THREADS
  1569. #ifdef HAVE_GETHOSTBYNAME_R
  1570. #if   defined(HAVE_GETHOSTBYNAME_R_6_ARG)
  1571.     result = gethostbyaddr_r((char *)&addr.sin_addr,
  1572.         sizeof(addr.sin_addr),
  1573.         AF_INET, &hp_allocated, buf, buf_len,
  1574.         &h, &errnop);
  1575. #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
  1576.     h = gethostbyaddr_r((char *)&addr.sin_addr,
  1577.                 sizeof(addr.sin_addr),
  1578.                 AF_INET, 
  1579.                 &hp_allocated, buf, buf_len, &errnop);
  1580. #else /* HAVE_GETHOSTBYNAME_R_3_ARG */
  1581.     memset((void *) &data, '\0', sizeof(data));
  1582.     result = gethostbyaddr_r((char *)&addr.sin_addr,
  1583.         sizeof(addr.sin_addr),
  1584.         AF_INET, &hp_allocated, &data);
  1585.     h = (result != 0) ? NULL : &hp_allocated;
  1586. #endif
  1587. #else /* not HAVE_GETHOSTBYNAME_R */
  1588. #ifdef USE_GETHOSTBYNAME_LOCK
  1589.     PyThread_acquire_lock(gethostbyname_lock, 1);
  1590. #endif
  1591.     h = gethostbyaddr((char *)&addr.sin_addr,
  1592.               sizeof(addr.sin_addr),
  1593.               AF_INET);
  1594. #endif /* HAVE_GETHOSTBYNAME_R */
  1595.     Py_END_ALLOW_THREADS
  1596.     ret = gethost_common(h, &addr);
  1597. #ifdef USE_GETHOSTBYNAME_LOCK
  1598.     PyThread_release_lock(gethostbyname_lock);
  1599. #endif
  1600.     return ret;
  1601. }
  1602.  
  1603. static char gethostbyaddr_doc[] =
  1604. "gethostbyaddr(host) -> (name, aliaslist, addresslist)\n\
  1605. \n\
  1606. Return the true host name, a list of aliases, and a list of IP addresses,\n\
  1607. for a host.  The host argument is a string giving a host name or IP number.";
  1608.  
  1609.  
  1610. /* Python interface to getservbyname(name).
  1611.    This only returns the port number, since the other info is already
  1612.    known or not useful (like the list of aliases). */
  1613.  
  1614. /*ARGSUSED*/
  1615. static PyObject *
  1616. BUILD_FUNC_DEF_2(PySocket_getservbyname,PyObject *,self, PyObject *,args)
  1617. {
  1618.     char *name, *proto;
  1619.     struct servent *sp;
  1620.     if (!PyArg_Parse(args, "(ss)", &name, &proto))
  1621.         return NULL;
  1622.     Py_BEGIN_ALLOW_THREADS
  1623.     sp = getservbyname(name, proto);
  1624.     Py_END_ALLOW_THREADS
  1625.     if (sp == NULL) {
  1626.         PyErr_SetString(PySocket_Error, "service/proto not found");
  1627.         return NULL;
  1628.     }
  1629.     return PyInt_FromLong((long) ntohs(sp->s_port));
  1630. }
  1631.  
  1632. static char getservbyname_doc[] =
  1633. "getservbyname(servicename, protocolname) -> integer\n\
  1634. \n\
  1635. Return a port number from a service name and protocol name.\n\
  1636. The protocol name should be 'tcp' or 'udp'.";
  1637.  
  1638.  
  1639. /* Python interface to getprotobyname(name).
  1640.    This only returns the protocol number, since the other info is
  1641.    already known or not useful (like the list of aliases). */
  1642.  
  1643. /*ARGSUSED*/
  1644. static PyObject *
  1645. BUILD_FUNC_DEF_2(PySocket_getprotobyname,PyObject *,self, PyObject *,args)
  1646. {
  1647.     char *name;
  1648.     struct protoent *sp;
  1649. #ifdef __BEOS__
  1650. /* Not available in BeOS yet. - [cjh] */
  1651.     PyErr_SetString( PySocket_Error, "getprotobyname not supported" );
  1652.     return NULL;
  1653. #else
  1654.     if (!PyArg_Parse(args, "s", &name))
  1655.         return NULL;
  1656.     Py_BEGIN_ALLOW_THREADS
  1657.     sp = getprotobyname(name);
  1658.     Py_END_ALLOW_THREADS
  1659.     if (sp == NULL) {
  1660.         PyErr_SetString(PySocket_Error, "protocol not found");
  1661.         return NULL;
  1662.     }
  1663.     return PyInt_FromLong((long) sp->p_proto);
  1664. #endif
  1665. }
  1666.  
  1667. static char getprotobyname_doc[] =
  1668. "getprotobyname(name) -> integer\n\
  1669. \n\
  1670. Return the protocol number for the named protocol.  (Rarely used.)";
  1671.  
  1672.  
  1673. /* Python interface to socket(family, type, proto).
  1674.    The third (protocol) argument is optional.
  1675.    Return a new socket object. */
  1676.  
  1677. /*ARGSUSED*/
  1678. static PyObject *
  1679. BUILD_FUNC_DEF_2(PySocket_socket,PyObject *,self, PyObject *,args)
  1680. {
  1681.     PySocketSockObject *s;
  1682. #ifdef MS_WINDOWS
  1683.     SOCKET fd;
  1684. #else
  1685.     int fd;
  1686. #endif
  1687.     int family, type, proto = 0;
  1688.     if (!PyArg_ParseTuple(args, "ii|i", &family, &type, &proto))
  1689.         return NULL;
  1690.     Py_BEGIN_ALLOW_THREADS
  1691.     fd = socket(family, type, proto);
  1692.     Py_END_ALLOW_THREADS
  1693. #ifdef MS_WINDOWS
  1694.     if (fd == INVALID_SOCKET)
  1695. #else
  1696.     if (fd < 0)
  1697. #endif
  1698.         return PySocket_Err();
  1699.     s = PySocketSock_New(fd, family, type, proto);
  1700.     /* If the object can't be created, don't forget to close the
  1701.        file descriptor again! */
  1702.     if (s == NULL)
  1703.         (void) close(fd);
  1704.     /* From now on, ignore SIGPIPE and let the error checking
  1705.        do the work. */
  1706. #ifdef SIGPIPE      
  1707.     (void) signal(SIGPIPE, SIG_IGN);
  1708. #endif   
  1709.     return (PyObject *) s;
  1710. }
  1711.  
  1712. static char socket_doc[] =
  1713. "socket(family, type[, proto]) -> socket object\n\
  1714. \n\
  1715. Open a socket of the given type.  The family argument specifies the\n\
  1716. address family; it is normally AF_INET, sometimes AF_UNIX.\n\
  1717. The type argument specifies whether this is a stream (SOCK_STREAM)\n\
  1718. or datagram (SOCK_DGRAM) socket.  The protocol argument defaults to 0,\n\
  1719. specifying the default protocol.";
  1720.  
  1721.  
  1722. #ifndef NO_DUP
  1723. /* Create a socket object from a numeric file description.
  1724.    Useful e.g. if stdin is a socket.
  1725.    Additional arguments as for socket(). */
  1726.  
  1727. /*ARGSUSED*/
  1728. static PyObject *
  1729. BUILD_FUNC_DEF_2(PySocket_fromfd,PyObject *,self, PyObject *,args)
  1730. {
  1731.     PySocketSockObject *s;
  1732.     int fd, family, type, proto = 0;
  1733.     if (!PyArg_ParseTuple(args, "iii|i", &fd, &family, &type, &proto))
  1734.         return NULL;
  1735.     /* Dup the fd so it and the socket can be closed independently */
  1736.     fd = dup(fd);
  1737.     if (fd < 0)
  1738.         return PySocket_Err();
  1739.     s = PySocketSock_New(fd, family, type, proto);
  1740.     /* From now on, ignore SIGPIPE and let the error checking
  1741.        do the work. */
  1742. #ifdef SIGPIPE      
  1743.     (void) signal(SIGPIPE, SIG_IGN);
  1744. #endif   
  1745.     return (PyObject *) s;
  1746. }
  1747.  
  1748. static char fromfd_doc[] =
  1749. "fromfd(fd, family, type[, proto]) -> socket object\n\
  1750. \n\
  1751. Create a socket object from the given file descriptor.\n\
  1752. The remaining arguments are the same as for socket().";
  1753.  
  1754. #endif /* NO_DUP */
  1755.  
  1756.  
  1757. static PyObject *
  1758. BUILD_FUNC_DEF_2(PySocket_ntohs, PyObject *, self, PyObject *, args)
  1759. {
  1760.     int x1, x2;
  1761.  
  1762.     if (!PyArg_Parse(args, "i", &x1)) {
  1763.         return NULL;
  1764.     }
  1765.     x2 = (int)ntohs((short)x1);
  1766.     return PyInt_FromLong(x2);
  1767. }
  1768.  
  1769. static char ntohs_doc[] =
  1770. "ntohs(integer) -> integer\n\
  1771. \n\
  1772. Convert a 16-bit integer from network to host byte order.";
  1773.  
  1774.  
  1775. static PyObject *
  1776. BUILD_FUNC_DEF_2(PySocket_ntohl, PyObject *, self, PyObject *, args)
  1777. {
  1778.     int x1, x2;
  1779.  
  1780.     if (!PyArg_Parse(args, "i", &x1)) {
  1781.         return NULL;
  1782.     }
  1783.     x2 = ntohl(x1);
  1784.     return PyInt_FromLong(x2);
  1785. }
  1786.  
  1787. static char ntohl_doc[] =
  1788. "ntohl(integer) -> integer\n\
  1789. \n\
  1790. Convert a 32-bit integer from network to host byte order.";
  1791.  
  1792.  
  1793. static PyObject *
  1794. BUILD_FUNC_DEF_2(PySocket_htons, PyObject *, self, PyObject *, args)
  1795. {
  1796.     int x1, x2;
  1797.  
  1798.     if (!PyArg_Parse(args, "i", &x1)) {
  1799.         return NULL;
  1800.     }
  1801.     x2 = (int)htons((short)x1);
  1802.     return PyInt_FromLong(x2);
  1803. }
  1804.  
  1805. static char htons_doc[] =
  1806. "htons(integer) -> integer\n\
  1807. \n\
  1808. Convert a 16-bit integer from host to network byte order.";
  1809.  
  1810.  
  1811. static PyObject *
  1812. BUILD_FUNC_DEF_2(PySocket_htonl, PyObject *, self, PyObject *, args)
  1813. {
  1814.     int x1, x2;
  1815.  
  1816.     if (!PyArg_Parse(args, "i", &x1)) {
  1817.         return NULL;
  1818.     }
  1819.     x2 = htonl(x1);
  1820.     return PyInt_FromLong(x2);
  1821. }
  1822.  
  1823. static char htonl_doc[] =
  1824. "htonl(integer) -> integer\n\
  1825. \n\
  1826. Convert a 32-bit integer from host to network byte order.";
  1827.  
  1828.  
  1829. /* List of functions exported by this module. */
  1830.  
  1831. static PyMethodDef PySocket_methods[] = {
  1832.     {"gethostbyname",    PySocket_gethostbyname, 0, gethostbyname_doc},
  1833.     {"gethostbyname_ex",    PySocket_gethostbyname_ex, 0, ghbn_ex_doc},
  1834.     {"gethostbyaddr",    PySocket_gethostbyaddr, 0, gethostbyaddr_doc},
  1835.     {"gethostname",        PySocket_gethostname, 0, gethostname_doc},
  1836.     {"getservbyname",    PySocket_getservbyname, 0, getservbyname_doc},
  1837.     {"getprotobyname",    PySocket_getprotobyname, 0,getprotobyname_doc},
  1838.     {"socket",        PySocket_socket, 1, socket_doc},
  1839. #ifndef NO_DUP
  1840.     {"fromfd",        PySocket_fromfd, 1, fromfd_doc},
  1841. #endif
  1842.     {"ntohs",        PySocket_ntohs, 0, ntohs_doc},
  1843.     {"ntohl",        PySocket_ntohl, 0, ntohl_doc},
  1844.     {"htons",        PySocket_htons, 0, htons_doc},
  1845.     {"htonl",        PySocket_htonl, 0, htonl_doc},
  1846.     {NULL,            NULL}         /* Sentinel */
  1847. };
  1848.  
  1849.  
  1850. /* Convenience routine to export an integer value.
  1851.  *
  1852.  * Errors are silently ignored, for better or for worse...
  1853.  */
  1854. static void
  1855. BUILD_FUNC_DEF_3(insint,PyObject *,d, char *,name, int,value)
  1856. {
  1857.     PyObject *v = PyInt_FromLong((long) value);
  1858.     if (!v || PyDict_SetItemString(d, name, v))
  1859.         PyErr_Clear();
  1860.  
  1861.     Py_XDECREF(v);
  1862. }
  1863.  
  1864.  
  1865. #ifdef MS_WINDOWS
  1866.  
  1867. /* Additional initialization and cleanup for NT/Windows */
  1868.  
  1869. static void
  1870. NTcleanup()
  1871. {
  1872.     WSACleanup();
  1873. }
  1874.  
  1875. static int
  1876. NTinit()
  1877. {
  1878.     WSADATA WSAData;
  1879.     int ret;
  1880.     char buf[100];
  1881.     ret = WSAStartup(0x0101, &WSAData);
  1882.     switch (ret) {
  1883.     case 0:    /* no error */
  1884.         atexit(NTcleanup);
  1885.         return 1;
  1886.     case WSASYSNOTREADY:
  1887.         PyErr_SetString(PyExc_ImportError,
  1888.                 "WSAStartup failed: network not ready");
  1889.         break;
  1890.     case WSAVERNOTSUPPORTED:
  1891.     case WSAEINVAL:
  1892.         PyErr_SetString(PyExc_ImportError,
  1893.             "WSAStartup failed: requested version not supported");
  1894.         break;
  1895.     default:
  1896.         sprintf(buf, "WSAStartup failed: error code %d", ret);
  1897.         PyErr_SetString(PyExc_ImportError, buf);
  1898.         break;
  1899.     }
  1900.     return 0;
  1901. }
  1902.  
  1903. #endif /* MS_WINDOWS */
  1904.  
  1905. #if defined(PYOS_OS2)
  1906.  
  1907. /* Additional initialization and cleanup for OS/2 */
  1908.  
  1909. static void
  1910. OS2cleanup()
  1911. {
  1912.     /* No cleanup is necessary for OS/2 Sockets */
  1913. }
  1914.  
  1915. static int
  1916. OS2init()
  1917. {
  1918.     char reason[64];
  1919.     int rc = sock_init();
  1920.  
  1921.     if (rc == 0) {
  1922.         atexit(OS2cleanup);
  1923.         return 1; /* Indicate Success */
  1924.     }
  1925.  
  1926.     sprintf(reason, "OS/2 TCP/IP Error# %d", sock_errno());
  1927.     PyErr_SetString(PyExc_ImportError, reason);
  1928.  
  1929.     return 0;  /* Indicate Failure */
  1930. }
  1931.  
  1932. #endif /* PYOS_OS2 */
  1933.  
  1934.  
  1935. /* Initialize this module.
  1936.  *   This is called when the first 'import socket' is done,
  1937.  *   via a table in config.c, if config.c is compiled with USE_SOCKET
  1938.  *   defined.
  1939.  *
  1940.  *   For MS_WINDOWS (which means any Windows variant), this module
  1941.  *   is actually called "_socket", and there's a wrapper "socket.py"
  1942.  *   which implements some missing functionality (such as makefile(),
  1943.  *   dup() and fromfd()).  The import of "_socket" may fail with an
  1944.  *   ImportError exception if initialization of WINSOCK fails.  When
  1945.  *   WINSOCK is initialized succesfully, a call to WSACleanup() is
  1946.  *   scheduled to be made at exit time.
  1947.  *
  1948.  *   For OS/2, this module is also called "_socket" and uses a wrapper
  1949.  *   "socket.py" which implements that functionality that is missing
  1950.  *   when PC operating systems don't put socket descriptors in the
  1951.  *   operating system's filesystem layer.
  1952.  */
  1953.  
  1954. static char module_doc[] =
  1955. "This module provides socket operations and some related functions.\n\
  1956. On Unix, it supports IP (Internet Protocol) and Unix domain sockets.\n\
  1957. On other systems, it only supports IP.\n\
  1958. \n\
  1959. Functions:\n\
  1960. \n\
  1961. socket() -- create a new socket object\n\
  1962. fromfd() -- create a socket object from an open file descriptor (*)\n\
  1963. gethostname() -- return the current hostname\n\
  1964. gethostbyname() -- map a hostname to its IP number\n\
  1965. gethostbyaddr() -- map an IP number or hostname to DNS info\n\
  1966. getservbyname() -- map a service name and a protocol name to a port number\n\
  1967. getprotobyname() -- mape a protocol name (e.g. 'tcp') to a number\n\
  1968. ntohs(), ntohl() -- convert 16, 32 bit int from network to host byte order\n\
  1969. htons(), htonl() -- convert 16, 32 bit int from host to network byte order\n\
  1970. \n\
  1971. (*) not available on all platforms!)\n\
  1972. \n\
  1973. Special objects:\n\
  1974. \n\
  1975. SocketType -- type object for socket objects\n\
  1976. error -- exception raised for I/O errors\n\
  1977. \n\
  1978. Integer constants:\n\
  1979. \n\
  1980. AF_INET, AF_UNIX -- socket domains (first argument to socket() call)\n\
  1981. SOCK_STREAM, SOCK_DGRAM, SOCK_RAW -- socket types (second argument)\n\
  1982. \n\
  1983. Many other constants may be defined; these may be used in calls to\n\
  1984. the setsockopt() and getsockopt() methods.\n\
  1985. ";
  1986.  
  1987. static char sockettype_doc[] =
  1988. "A socket represents one endpoint of a network connection.\n\
  1989. \n\
  1990. Methods:\n\
  1991. \n\
  1992. accept() -- accept a connection, returning new socket and client address\n\
  1993. bind() -- bind the socket to a local address\n\
  1994. close() -- close the socket\n\
  1995. connect() -- connect the socket to a remote address\n\
  1996. connect_ex() -- connect, return an error code instead of an exception \n\
  1997. dup() -- return a new socket object identical to the current one (*)\n\
  1998. fileno() -- return underlying file descriptor\n\
  1999. getpeername() -- return remote address (*)\n\
  2000. getsockname() -- return local address\n\
  2001. getsockopt() -- get socket options\n\
  2002. listen() -- start listening for incoming connections\n\
  2003. makefile() -- return a file object corresponding tot the socket (*)\n\
  2004. recv() -- receive data\n\
  2005. recvfrom() -- receive data and sender's address\n\
  2006. send() -- send data\n\
  2007. sendto() -- send data to a given address\n\
  2008. setblocking() -- set or clear the blocking I/O flag\n\
  2009. setsockopt() -- set socket options\n\
  2010. shutdown() -- shut down traffic in one or both directions\n\
  2011. \n\
  2012. (*) not available on all platforms!)";
  2013.  
  2014. DL_EXPORT(void)
  2015. #if defined(MS_WINDOWS) || defined(PYOS_OS2) || defined(__BEOS__)
  2016. init_socket()
  2017. #else
  2018. initsocket()
  2019. #endif
  2020. {
  2021.     PyObject *m, *d;
  2022. #ifdef MS_WINDOWS
  2023.     if (!NTinit())
  2024.         return;
  2025.     m = Py_InitModule3("_socket", PySocket_methods, module_doc);
  2026. #else
  2027. #if defined(__TOS_OS2__)
  2028.     if (!OS2init())
  2029.         return;
  2030.     m = Py_InitModule3("_socket", PySocket_methods, module_doc);
  2031. #else
  2032. #if defined(__BEOS__)
  2033.     m = Py_InitModule3("_socket", PySocket_methods, module_doc);
  2034. #else
  2035.     m = Py_InitModule3("socket", PySocket_methods, module_doc);
  2036. #endif /* __BEOS__ */
  2037. #endif
  2038. #endif
  2039.     d = PyModule_GetDict(m);
  2040.     PySocket_Error = PyErr_NewException("socket.error", NULL, NULL);
  2041.     if (PySocket_Error == NULL)
  2042.         return;
  2043.     PyDict_SetItemString(d, "error", PySocket_Error);
  2044.     PySocketSock_Type.ob_type = &PyType_Type;
  2045.     PySocketSock_Type.tp_doc = sockettype_doc;
  2046.     Py_INCREF(&PySocketSock_Type);
  2047.     if (PyDict_SetItemString(d, "SocketType",
  2048.                  (PyObject *)&PySocketSock_Type) != 0)
  2049.         return;
  2050.     insint(d, "AF_INET", AF_INET);
  2051. #ifdef AF_UNIX
  2052.     insint(d, "AF_UNIX", AF_UNIX);
  2053. #endif /* AF_UNIX */
  2054.     insint(d, "SOCK_STREAM", SOCK_STREAM);
  2055.     insint(d, "SOCK_DGRAM", SOCK_DGRAM);
  2056. #ifndef __BEOS__
  2057. /* We have incomplete socket support. */
  2058.     insint(d, "SOCK_RAW", SOCK_RAW);
  2059.     insint(d, "SOCK_SEQPACKET", SOCK_SEQPACKET);
  2060.     insint(d, "SOCK_RDM", SOCK_RDM);
  2061. #endif
  2062.  
  2063. #ifdef    SO_DEBUG
  2064.     insint(d, "SO_DEBUG", SO_DEBUG);
  2065. #endif
  2066. #ifdef    SO_ACCEPTCONN
  2067.     insint(d, "SO_ACCEPTCONN", SO_ACCEPTCONN);
  2068. #endif
  2069. #ifdef    SO_REUSEADDR
  2070.     insint(d, "SO_REUSEADDR", SO_REUSEADDR);
  2071. #endif
  2072. #ifdef    SO_KEEPALIVE
  2073.     insint(d, "SO_KEEPALIVE", SO_KEEPALIVE);
  2074. #endif
  2075. #ifdef    SO_DONTROUTE
  2076.     insint(d, "SO_DONTROUTE", SO_DONTROUTE);
  2077. #endif
  2078. #ifdef    SO_BROADCAST
  2079.     insint(d, "SO_BROADCAST", SO_BROADCAST);
  2080. #endif
  2081. #ifdef    SO_USELOOPBACK
  2082.     insint(d, "SO_USELOOPBACK", SO_USELOOPBACK);
  2083. #endif
  2084. #ifdef    SO_LINGER
  2085.     insint(d, "SO_LINGER", SO_LINGER);
  2086. #endif
  2087. #ifdef    SO_OOBINLINE
  2088.     insint(d, "SO_OOBINLINE", SO_OOBINLINE);
  2089. #endif
  2090. #ifdef    SO_REUSEPORT
  2091.     insint(d, "SO_REUSEPORT", SO_REUSEPORT);
  2092. #endif
  2093.  
  2094. #ifdef    SO_SNDBUF
  2095.     insint(d, "SO_SNDBUF", SO_SNDBUF);
  2096. #endif
  2097. #ifdef    SO_RCVBUF
  2098.     insint(d, "SO_RCVBUF", SO_RCVBUF);
  2099. #endif
  2100. #ifdef    SO_SNDLOWAT
  2101.     insint(d, "SO_SNDLOWAT", SO_SNDLOWAT);
  2102. #endif
  2103. #ifdef    SO_RCVLOWAT
  2104.     insint(d, "SO_RCVLOWAT", SO_RCVLOWAT);
  2105. #endif
  2106. #ifdef    SO_SNDTIMEO
  2107.     insint(d, "SO_SNDTIMEO", SO_SNDTIMEO);
  2108. #endif
  2109. #ifdef    SO_RCVTIMEO
  2110.     insint(d, "SO_RCVTIMEO", SO_RCVTIMEO);
  2111. #endif
  2112. #ifdef    SO_ERROR
  2113.     insint(d, "SO_ERROR", SO_ERROR);
  2114. #endif
  2115. #ifdef    SO_TYPE
  2116.     insint(d, "SO_TYPE", SO_TYPE);
  2117. #endif
  2118.  
  2119.     /* Maximum number of connections for "listen" */
  2120. #ifdef    SOMAXCONN
  2121.     insint(d, "SOMAXCONN", SOMAXCONN);
  2122. #else
  2123.     insint(d, "SOMAXCONN", 5);    /* Common value */
  2124. #endif
  2125.  
  2126.     /* Flags for send, recv */
  2127. #ifdef    MSG_OOB
  2128.     insint(d, "MSG_OOB", MSG_OOB);
  2129. #endif
  2130. #ifdef    MSG_PEEK
  2131.     insint(d, "MSG_PEEK", MSG_PEEK);
  2132. #endif
  2133. #ifdef    MSG_DONTROUTE
  2134.     insint(d, "MSG_DONTROUTE", MSG_DONTROUTE);
  2135. #endif
  2136. #ifdef    MSG_EOR
  2137.     insint(d, "MSG_EOR", MSG_EOR);
  2138. #endif
  2139. #ifdef    MSG_TRUNC
  2140.     insint(d, "MSG_TRUNC", MSG_TRUNC);
  2141. #endif
  2142. #ifdef    MSG_CTRUNC
  2143.     insint(d, "MSG_CTRUNC", MSG_CTRUNC);
  2144. #endif
  2145. #ifdef    MSG_WAITALL
  2146.     insint(d, "MSG_WAITALL", MSG_WAITALL);
  2147. #endif
  2148. #ifdef    MSG_BTAG
  2149.     insint(d, "MSG_BTAG", MSG_BTAG);
  2150. #endif
  2151. #ifdef    MSG_ETAG
  2152.     insint(d, "MSG_ETAG", MSG_ETAG);
  2153. #endif
  2154.  
  2155.     /* Protocol level and numbers, usable for [gs]etsockopt */
  2156. /* Sigh -- some systems (e.g. Linux) use enums for these. */
  2157. #ifdef    SOL_SOCKET
  2158.     insint(d, "SOL_SOCKET", SOL_SOCKET);
  2159. #endif
  2160. #ifdef    IPPROTO_IP
  2161.     insint(d, "IPPROTO_IP", IPPROTO_IP);
  2162. #else
  2163.     insint(d, "IPPROTO_IP", 0);
  2164. #endif
  2165. #ifdef    IPPROTO_ICMP
  2166.     insint(d, "IPPROTO_ICMP", IPPROTO_ICMP);
  2167. #else
  2168.     insint(d, "IPPROTO_ICMP", 1);
  2169. #endif
  2170. #ifdef    IPPROTO_IGMP
  2171.     insint(d, "IPPROTO_IGMP", IPPROTO_IGMP);
  2172. #endif
  2173. #ifdef    IPPROTO_GGP
  2174.     insint(d, "IPPROTO_GGP", IPPROTO_GGP);
  2175. #endif
  2176. #ifdef    IPPROTO_TCP
  2177.     insint(d, "IPPROTO_TCP", IPPROTO_TCP);
  2178. #else
  2179.     insint(d, "IPPROTO_TCP", 6);
  2180. #endif
  2181. #ifdef    IPPROTO_EGP
  2182.     insint(d, "IPPROTO_EGP", IPPROTO_EGP);
  2183. #endif
  2184. #ifdef    IPPROTO_PUP
  2185.     insint(d, "IPPROTO_PUP", IPPROTO_PUP);
  2186. #endif
  2187. #ifdef    IPPROTO_UDP
  2188.     insint(d, "IPPROTO_UDP", IPPROTO_UDP);
  2189. #else
  2190.     insint(d, "IPPROTO_UDP", 17);
  2191. #endif
  2192. #ifdef    IPPROTO_IDP
  2193.     insint(d, "IPPROTO_IDP", IPPROTO_IDP);
  2194. #endif
  2195. #ifdef    IPPROTO_HELLO
  2196.     insint(d, "IPPROTO_HELLO", IPPROTO_HELLO);
  2197. #endif
  2198. #ifdef    IPPROTO_ND
  2199.     insint(d, "IPPROTO_ND", IPPROTO_ND);
  2200. #endif
  2201. #ifdef    IPPROTO_TP
  2202.     insint(d, "IPPROTO_TP", IPPROTO_TP);
  2203. #endif
  2204. #ifdef    IPPROTO_XTP
  2205.     insint(d, "IPPROTO_XTP", IPPROTO_XTP);
  2206. #endif
  2207. #ifdef    IPPROTO_EON
  2208.     insint(d, "IPPROTO_EON", IPPROTO_EON);
  2209. #endif
  2210. #ifdef    IPPROTO_BIP
  2211.     insint(d, "IPPROTO_BIP", IPPROTO_BIP);
  2212. #endif
  2213. /**/
  2214. #ifdef    IPPROTO_RAW
  2215.     insint(d, "IPPROTO_RAW", IPPROTO_RAW);
  2216. #else
  2217.     insint(d, "IPPROTO_RAW", 255);
  2218. #endif
  2219. #ifdef    IPPROTO_MAX
  2220.     insint(d, "IPPROTO_MAX", IPPROTO_MAX);
  2221. #endif
  2222.  
  2223.     /* Some port configuration */
  2224. #ifdef    IPPORT_RESERVED
  2225.     insint(d, "IPPORT_RESERVED", IPPORT_RESERVED);
  2226. #else
  2227.     insint(d, "IPPORT_RESERVED", 1024);
  2228. #endif
  2229. #ifdef    IPPORT_USERRESERVED
  2230.     insint(d, "IPPORT_USERRESERVED", IPPORT_USERRESERVED);
  2231. #else
  2232.     insint(d, "IPPORT_USERRESERVED", 5000);
  2233. #endif
  2234.  
  2235.     /* Some reserved IP v.4 addresses */
  2236. #ifdef    INADDR_ANY
  2237.     insint(d, "INADDR_ANY", INADDR_ANY);
  2238. #else
  2239.     insint(d, "INADDR_ANY", 0x00000000);
  2240. #endif
  2241. #ifdef    INADDR_BROADCAST
  2242.     insint(d, "INADDR_BROADCAST", INADDR_BROADCAST);
  2243. #else
  2244.     insint(d, "INADDR_BROADCAST", 0xffffffff);
  2245. #endif
  2246. #ifdef    INADDR_LOOPBACK
  2247.     insint(d, "INADDR_LOOPBACK", INADDR_LOOPBACK);
  2248. #else
  2249.     insint(d, "INADDR_LOOPBACK", 0x7F000001);
  2250. #endif
  2251. #ifdef    INADDR_UNSPEC_GROUP
  2252.     insint(d, "INADDR_UNSPEC_GROUP", INADDR_UNSPEC_GROUP);
  2253. #else
  2254.     insint(d, "INADDR_UNSPEC_GROUP", 0xe0000000);
  2255. #endif
  2256. #ifdef    INADDR_ALLHOSTS_GROUP
  2257.     insint(d, "INADDR_ALLHOSTS_GROUP", INADDR_ALLHOSTS_GROUP);
  2258. #else
  2259.     insint(d, "INADDR_ALLHOSTS_GROUP", 0xe0000001);
  2260. #endif
  2261. #ifdef    INADDR_MAX_LOCAL_GROUP
  2262.     insint(d, "INADDR_MAX_LOCAL_GROUP", INADDR_MAX_LOCAL_GROUP);
  2263. #else
  2264.     insint(d, "INADDR_MAX_LOCAL_GROUP", 0xe00000ff);
  2265. #endif
  2266. #ifdef    INADDR_NONE
  2267.     insint(d, "INADDR_NONE", INADDR_NONE);
  2268. #else
  2269.     insint(d, "INADDR_NONE", 0xffffffff);
  2270. #endif
  2271.  
  2272.     /* IP [gs]etsockopt options */
  2273. #ifdef    IP_OPTIONS
  2274.     insint(d, "IP_OPTIONS", IP_OPTIONS);
  2275. #endif
  2276. #ifdef    IP_HDRINCL
  2277.     insint(d, "IP_HDRINCL", IP_HDRINCL);
  2278. #endif
  2279. #ifdef    IP_TOS
  2280.     insint(d, "IP_TOS", IP_TOS);
  2281. #endif
  2282. #ifdef    IP_TTL
  2283.     insint(d, "IP_TTL", IP_TTL);
  2284. #endif
  2285. #ifdef    IP_RECVOPTS
  2286.     insint(d, "IP_RECVOPTS", IP_RECVOPTS);
  2287. #endif
  2288. #ifdef    IP_RECVRETOPTS
  2289.     insint(d, "IP_RECVRETOPTS", IP_RECVRETOPTS);
  2290. #endif
  2291. #ifdef    IP_RECVDSTADDR
  2292.     insint(d, "IP_RECVDSTADDR", IP_RECVDSTADDR);
  2293. #endif
  2294. #ifdef    IP_RETOPTS
  2295.     insint(d, "IP_RETOPTS", IP_RETOPTS);
  2296. #endif
  2297. #ifdef    IP_MULTICAST_IF
  2298.     insint(d, "IP_MULTICAST_IF", IP_MULTICAST_IF);
  2299. #endif
  2300. #ifdef    IP_MULTICAST_TTL
  2301.     insint(d, "IP_MULTICAST_TTL", IP_MULTICAST_TTL);
  2302. #endif
  2303. #ifdef    IP_MULTICAST_LOOP
  2304.     insint(d, "IP_MULTICAST_LOOP", IP_MULTICAST_LOOP);
  2305. #endif
  2306. #ifdef    IP_ADD_MEMBERSHIP
  2307.     insint(d, "IP_ADD_MEMBERSHIP", IP_ADD_MEMBERSHIP);
  2308. #endif
  2309. #ifdef    IP_DROP_MEMBERSHIP
  2310.     insint(d, "IP_DROP_MEMBERSHIP", IP_DROP_MEMBERSHIP);
  2311. #endif
  2312.  
  2313.     /* Initialize gethostbyname lock */
  2314. #ifdef USE_GETHOSTBYNAME_LOCK
  2315.     gethostbyname_lock = PyThread_allocate_lock();
  2316. #endif
  2317. }
  2318.